<template>
  <!-- 弹框 -->
  <el-drawer title="管理产品分类" v-model="dialogVisible" size="40%">
    <div class="flex justify-end mb-5">
      <el-button type="primary" @click="handleOpenDialog">新增分类</el-button>
    </div>
    <base-page-table
      :table-data="tableData"
      :table-columns-data="tableColumnsData"
      :loading="loading"
      :page-num="queryParams.pageNum"
      :page-size="queryParams.pageSize"
      :total="queryParams.total"
      @handleQuery="handleQuery"
    >
      <template #operation="scope">
        <el-button type="primary" link size="small" icon="edit" @click.stop="handleEdit(scope.row)">
          编辑
        </el-button>
        <el-button
          type="danger"
          link
          size="small"
          icon="delete"
          @click.stop="handleDelete(scope.row.id)"
        >
          删除
        </el-button>
      </template>
    </base-page-table>
    <!-- 抽屉组件（添加/编辑表单） -->
    <el-dialog v-model="categoryVisible" :title="categoryTitle" direction="rtl" width="40%">
      <el-form :model="categoryFormData" label-width="80px">
        <el-form-item label="上级分类">
          <el-select v-model="categoryFormData.parentId" placeholder="请选择上级分类">
            <el-option
              v-for="item in parentCategoryRoot"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" required>
          <el-input v-model="categoryFormData.name" />
        </el-form-item>
        <!-- <el-form-item label="排序">
          <el-input-number v-model="categoryFormData.sort" :min="0" />
        </el-form-item> -->
        <div class="flex justify-end">
          <el-form-item>
            <el-button type="primary" @click="handleConfirm">确认</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>
  </el-drawer>
</template>

<script setup>
import EquityMallAPI from "@/api/equitymall";
const emit = defineEmits(["update:visible", "updateTableData"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  tableData: {
    type: Array,
    default: [],
  },
});
const dialogVisible = ref(props.visible);
watch(dialogVisible, (newVal) => {
  emit("update:visible", newVal);
});
watchEffect(() => {
  dialogVisible.value = props.visible;
});
const tableData = ref(props.tableData);
watchEffect(() => {
  tableData.value = props.tableData;
});
const tableColumnsData = ref([
  {
    label: "分类名称",
    prop: "name",
    width: 200,
    align: "left",
  },
  // {
  //   label: "分类排序",
  //   prop: "sort",
  //   align: "left",
  // },
  {
    label: "操作",
    prop: "name",
    align: "center",
    customSlot: "operation",
  },
]);
const loading = ref(false);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10000,
  total: 0,
});

/**
 *
 * 新增产品分类- 弹框相关
 *
 */
const categoryVisible = ref(false);
const categoryTitle = ref("");
const categoryFormData = ref({
  parentId: null,
  name: "",
  sort: 0,
});
const handleOpenDialog = () => {
  categoryFormData.value = {
    parentId: null,
    name: "",
    sort: 0,
  };
  categoryVisible.value = true;
  categoryTitle.value = "新增产品分类";
};
// 编辑产品分类
const handleEdit = (row) => {
  categoryVisible.value = true;
  categoryTitle.value = "编辑产品分类";
  categoryFormData.value = {
    id: row.id,
    parentId: row.parentId,
    name: row.name,
    sort: row?.sort,
  };
};
// 删除产品分类
const handleDelete = (id) => {
  ElMessageBox.confirm("确定删除该产品分类吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    console.log(id);
    deleteProductCategory(id);
  });
};
// 确认添加还是编辑
const handleConfirm = () => {
  if (categoryTitle.value === "新增产品分类") {
    addProductCategory();
  } else {
    updateProductCategory();
  }
};
// 添加产品分类
const addProductCategory = async () => {
  try {
    await EquityMallAPI.addProductCategory({
      parentId: categoryFormData.value.parentId ?? null,
      name: categoryFormData.value.name,
    });
    ElMessage.success("添加成功");
    categoryVisible.value = false;
    nextTick(() => {
      emit("updateTableData");
    });
  } catch (error) {
    console.error(error);
  } finally {
  }
};
// 编辑产品分类
const updateProductCategory = async () => {
  try {
    await EquityMallAPI.updateProductCategoryById({
      id: categoryFormData.value.id,
      parentId: categoryFormData.value.parentId ?? null,
      name: categoryFormData.value.name,
    });
    ElMessage.success("编辑成功");
    categoryVisible.value = false;
    nextTick(() => {
      emit("updateTableData");
    });
  } catch (error) {
    console.error(error);
  }
};
const deleteProductCategory = async (id) => {
  try {
    await EquityMallAPI.deleteProductCategoryById(id);
    ElMessage.success("删除成功");
    categoryVisible.value = false;
    emit("updateTableData");
  } catch (error) {
    console.error(error);
  }
};
const parentCategoryRoot = ref([]);
const getProductCategoryRoot = async () => {
  try {
    const res = await EquityMallAPI.getProductCategoryRoot();
    console.log(res);
    parentCategoryRoot.value = res;
  } catch (error) {
    console.error(error);
  }
};
onMounted(() => {
  getProductCategoryRoot();
});
</script>

<style scoped>
.margin-top {
  margin-top: 20px;
}
</style>
